<template>
  <el-dialog
    top="30px"
    append-to-body
    :close-on-click-modal="false"
    title="合同重做"
    :before-close="beforeClose"
    :visible.sync="visible"
  >
    <div v-loading="loading">
      <div class="mb-2">
        <el-button @click="getData()" icon="el-icon-refresh" :loading="loading">刷新</el-button>
      </div>
      <div v-for="(p, index) of contracts" :key="index" class="p-1">
        <div>
          <el-checkbox v-model="p.checked">{{ p.label }}</el-checkbox>
          <el-button size="mini" @click="handleView(p)">查看合同</el-button>
        </div>

        <div v-if="p.checked">
          <el-input type="textarea" v-model="p.re_sign_des" placeholder="合同重签原因"></el-input>
        </div>
      </div>

      <div class="mt-5">
        <el-button class="btn-long" type="primary" @click="submit">提交</el-button>
        <el-button class="btn-long" @click="beforeClose">取消</el-button>
      </div>
    </div>

    <el-dialog
      :visible.sync="viewVisible"
      :close-on-click-modal="false"
      append-to-body
      top="30px"
      width="80%"
    >
      <pdf-view
        :contract-id="docId"
        :query-id="queryId"
        :sig-no="signNo"
        :view-mode="true"
      ></pdf-view>
    </el-dialog>
  </el-dialog>
</template>

<script>
import PdfView from '@/credit/views/county/unionProvince/components/PdfView'
import { mapGetters } from 'vuex'
export const enumContractType = {
  1: '保证担保',
  2: '质押合同',
  3: '抵押合同',
  4: '留置协议',
}

export const enumLetterType = {
  1: '电子保函',
  2: '联保函',
}
export default {
  props: {
    visible: Boolean,
    queryId: String,
    noApproval: {
      type: Boolean,
      default: false,
    },
  },
  components: {
    PdfView,
  },
  data() {
    return {
      loading: false,
      contracts: [],
      docId: '',
      signNo: '',
      viewVisible: false,
    }
  },
  watch: {
    queryId: {
      handler: function () {
        this.getData()
      },
      immediate: true,
    },
  },
  computed: {
    ...mapGetters(['guardDatas', 'entrustContract', 'user']),
  },
  created() {},
  methods: {
    handleView(p) {
      this.docId = p.doc_id
      this.signNo = p.sign_no
      this.viewVisible = true
    },
    getData() {
      if (!this.queryId) {
        return
      }
      this.contracts = []
      this.loading = true
      Promise.all([
        this.$api.getData(
          'credit',
          'ele_letter_info',
          {
            'customer_related_id.eq': this.queryId,
          },
          { create_time: 'desc' }
        ),
        this.$api.getData(
          'credit',
          'loan_notice',
          { 'customer_related_id.eq': this.queryId },
          { create_time: 'desc' }
        ),
        this.$store.dispatch('getGuardsData', this.queryId),
        this.$store.dispatch('getEntrustContract', this.queryId),
      ])
        .then(([res, loan]) => {
          const letters = res?.data ?? []
          const loanData = loan?.data?.[0] ?? {}
          this.contracts.push({
            label: '委托合同',
            sign_no: this.entrustContract.sign_no,
            doc_id: this.entrustContract.doc_id,
            related_id: this.entrustContract.entrust_contract_id,
            sign_no_type: 1,
            re_sign_des: '',
            checked: false,
          })
          for (let p of this.guardDatas) {
            this.contracts.push({
              label: `${enumContractType[p.gua_method]}-${p.gua_entity}`,
              sign_no: p.sign_no,
              doc_id: p.doc_id,
              related_id: p.gua_contract_id,
              sign_no_type: 2,
              re_sign_des: '',
              checked: false,
            })
          }
          for (let p of letters) {
            this.contracts.push({
              label: `${enumLetterType[p.ele_letter_type]}-${p.sign_date}`,
              sign_no: p.sign_no,
              doc_id: p.doc_id,
              related_id: p.ele_letter_info_id,
              sign_no_type: +p.ele_letter_type === 1 ? 4 : 3,
              re_sign_des: '',
              checked: false,
            })
          }
          if (loanData.loan_notice_id) {
            this.contracts.push({
              label: '放款通知书',
              sign_no: loanData.sign_no,
              doc_id: loanData.doc_id,
              related_id: loanData.loan_notice_id,
              sign_no_type: 5,
              re_sign_des: '',
              checked: false,
            })
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    submit() {
      const data = []
      for (let p of this.contracts) {
        if (p.checked && !p.re_sign_des) {
          return this.$message.warning(`请输入${p.label}的原因`)
        }
        if (p.checked) {
          data.push({
            sign_no: p.sign_no,
            doc_id: p.doc_id,
            related_id: p.related_id,
            sign_no_type: p.sign_no_type,
            re_sign_des: p.re_sign_des,
            re_sign_person: this.user.realName,
            re_sign_time: this.$utils.dateFormat(new Date()),
            customer_related_id: this.queryId,
            is_re_sign_dir: this.noApproval ? 1 : 0,
          })
        }
      }

      for (let p of data) {
        if (!p.re_sign_des) {
          return this.$message.warning(
            `请填写${enumContractType[p.gua_method]}-${p.gua_entity}的原因`
          )
        }
      }
      this.$utils
        .msgbox({
          message: `确定${this.noApproval ? '重签' : '重做'}所选择的合同？`,
          beforeClose: () => this.$api.addBatch('credit', 're_sign_record', data),
        })
        .then(() => {
          this.$message.success('提交成功！')
          this.handleSuccess()
        })
        .catch(() => this.$message.error(`操作失败，请重试！`))
    },
    beforeClose() {
      this.$emit('update:visible', false)
    },
    handleSuccess() {
      this.getData()
      this.$emit('success', true)
      this.beforeClose()
    },
  },
}
</script>
<style lang="scss" scoped></style>
